package com.fastjrun.security.authentication.wechat;

import com.fastjrun.security.authentication.mobile.MobileAuthenticationFilter;
import com.fastjrun.security.authentication.mobile.MobileAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用于组合其他关于微信登录的组件
 * @author javafun
 */
@Component
public class WechatAuthenticationConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    AuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Resource
    AuthenticationFailureHandler customAuthenticationFailureHandler;

    @Resource
    UserDetailsService wechatUserDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        WechatAuthenticationFilter wechatAuthenticationFilter = new WechatAuthenticationFilter();
        // 获取容器中已经存在的AuthenticationManager对象，并传入 wechatAuthenticationFilter 里面
        wechatAuthenticationFilter.setAuthenticationManager(
                http.getSharedObject(AuthenticationManager.class));
        // session重复登录 管理
        wechatAuthenticationFilter.setSessionAuthenticationStrategy(
                http.getSharedObject(SessionAuthenticationStrategy.class));

        // 传入 失败与成功处理器
        wechatAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        wechatAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

        // 构建一个WechatAuthenticationProvider实例，接收 wechatUserDetailsService 通过手机号查询用户信息
        WechatAuthenticationProvider provider = new WechatAuthenticationProvider();
        provider.setUserDetailsService(wechatUserDetailsService);

        // 将provider绑定到 HttpSecurity上，并将 手机号认证过滤器绑定到用户名密码认证过滤器之后
        http.authenticationProvider(provider)
                .addFilterAfter(wechatAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}
